package amap_utils

import (
	"errors"
	"fmt"
	"hft/e"
	maptool "hft/tools/map_tool"
	"net/url"
	"strconv"
	"strings"

	"github.com/tidwall/gjson"
)

// 获取ip
func GetIP(ip string) (city string, location string, err error) {
	data, err := maptool.NewAmapMapApi("/v3/ip", &url.Values{"ip": []string{ip}})
	if err != nil {
		return "", "", errors.New(e.AmapIpNotFound)
	}
	res := string(data)
	fmt.Println("ip", res)
	status := gjson.Get(res, "status").String()
	info := gjson.Get(res, "info").String()
	if status != "1" || info != "OK" {
		return "", "", errors.New(e.AmapIpNotFound)
	}
	nowCity := gjson.Get(res, "city").String()
	if nowCity == "[]" {
		return "", "", errors.New(e.AmapIpNotFound)
	}
	// 获取location
	rectangle := gjson.Get(res, "rectangle").String()
	var lat float64
	var lng float64
	if rectangle != "" {
		var strArr1 = strings.Split(rectangle, ";")
		var leftTop = strings.Split(strArr1[0], ",")
		var rightBottom = strings.Split(strArr1[1], ",")
		leftTopLat, _ := strconv.ParseFloat(leftTop[0], 64)
		rightBottomLat, _ := strconv.ParseFloat(rightBottom[0], 64)
		leftTopLng, _ := strconv.ParseFloat(leftTop[1], 64)
		rightBottomLng, _ := strconv.ParseFloat(rightBottom[1], 64)
		lat = (leftTopLat + rightBottomLat) / 2
		lng = (leftTopLng + rightBottomLng) / 2
	}
	fmt.Println(lat, lng)
	return nowCity, fmt.Sprintf("%v,%v", lat, lng), nil
}
